package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.constant.RefundLogConstant;
import com.tbit.uqbike.object.pojo.RefundLog;
import com.tbit.uqbike.object.pojo.RefundLogSum;
import com.tbit.uqbike.object.pojo.RideUserRefund;
import com.tbit.uqbike.object.pojo.TransactionLog;
import com.tbit.uqbike.object.pojo.dto.RefundLogDTO;
import com.tbit.uqbike.object.pojo.dto.RefundLogDownloadDTO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.RefundLogService;
import com.tbit.uqbike.webmanager.dao.capital.RefundLogDao;
import com.tbit.uqbike.webmanager.dao.log.RideRefundLogDao;
import com.tbit.uqbike.webmanager.dao.log.TransactionLogDao;
import com.tbit.uqbike.webmanager.util.BeanUtils;
import com.tbit.uqbike.webmanager.util.csv.CsvExportUtils;
import com.tbit.uqbike.webmanager.util.csv.entity.ExportHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.IntSupplier;

/**
 * @Author:BUGTian
 * @DATE: 2022/11/16
 */
@Service
public class RefundLogServiceImpl implements RefundLogService {

    @Autowired
    CsvExportUtils csvExportUtils;
    @Autowired
    private RefundLogDao refundLogDao;
    @Autowired
    private RideRefundLogDao rideRefundLogDao;
    @Autowired
    private TransactionLogDao transactionLogDao;

    @Override
    public PageResult<RefundLog> queryPage(RefundLogDTO refundLogDTO) {
        Integer page = refundLogDTO.getPage();
        Integer size = refundLogDTO.getSize();
        PageInfo<RefundLog> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> refundLogDao.queryList(refundLogDTO));
        return new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public RefundLogSum sumRefundLog(RefundLogDTO refundLogDTO) {
        //现金交易退款总金额
        Long cashRefundSumMoney = 0L;
        //现金交易退款总笔数
        Integer cashRefundSumCount = 0;
        //虚拟费用退款总金额
        Long virtualRefundSumMoney = 0L;
        //虚拟费用退款总笔数
        Integer virtualRefundSumCount = 0;
        Map<Integer, RefundLog> refundLogMap = refundLogDao.sumRefundLog(refundLogDTO);
        for (Map.Entry<Integer, RefundLog> entry : refundLogMap.entrySet()) {
            switch (entry.getKey()) {
                //虚拟退款的类型
                case RefundLogConstant.MANUAL_MODIFICATION_OF_THE_ORDER_TO_OFFSET_THE_COST_REFUND:
                case RefundLogConstant.REFUND_OF_OTHER_VIRTUAL_DEDUCTIBLE_EXPENSES:
                    virtualRefundSumMoney += entry.getValue() == null ? 0L : entry.getValue().getChangeMoney();
                    virtualRefundSumCount += entry.getValue() == null ? 0 : entry.getValue().getRefundId().intValue();
                    break;
                default:
                    cashRefundSumMoney += entry.getValue() == null ? 0L : entry.getValue().getChangeMoney();
                    cashRefundSumCount += entry.getValue() == null ? 0 : entry.getValue().getRefundId().intValue();
                    break;
            }
        }
        return new RefundLogSum(((double) cashRefundSumMoney / 100D), cashRefundSumCount, ((double) virtualRefundSumMoney / 100D), virtualRefundSumCount);
    }

    @Override
    public List<TransactionLog> selectTransactionLog(String businessNO) {
        return transactionLogDao.selectList(new QueryWrapper<TransactionLog>().eq("refundBusinessNO", businessNO));
    }

    @Override
    public String download(RefundLogDownloadDTO downloadDTO) {
        downloadDTO.setFileName("退款统计账单");
        File tempFile = csvExportUtils.getTempFile();
        try {
            File file = download(downloadDTO, tempFile);
            String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        } finally {
            FileUtil.del(tempFile);
        }
    }

    public File download(RefundLogDownloadDTO downloadDTO, File tempFile) {
        Date startTime = downloadDTO.getStartTime();
        Date endTime = downloadDTO.getEndTime();
        return csvExportUtils.export((baseEntity) -> {
            RefundLogDTO dto = BeanUtils.copyProperties(downloadDTO, RefundLogDTO.class);
            dto.setStartTime(baseEntity.getStartTime());
            dto.setEndTime(baseEntity.getEndTime());
            List<RefundLog> list = refundLogDao.queryList(dto);
            return list;
        }, RefundLog.class, startTime, endTime, tempFile, downloadDTO.getFileName());
    }


    @Override
    public String distributionDownload(RefundLogDownloadDTO downloadDTO) {
        downloadDTO.setFileName("骑行退款金额分布");
        Date startTime = downloadDTO.getStartTime();
        Date endTime = downloadDTO.getEndTime();
        Integer brandId = downloadDTO.getBrandId();
        String accountIds = downloadDTO.getAccountIds();
        File tempFile = csvExportUtils.getTempFile();
        IntSupplier countFn = () -> rideRefundLogDao.orderRefundDistributionCount(accountIds, startTime, endTime, brandId);
        try {
            ExportHandler<RideUserRefund> exportHandler = baseEntity -> rideRefundLogDao.selectOrderRefundDistribution(accountIds, baseEntity.getStartTime(), baseEntity.getEndTime(), brandId);
            File file = csvExportUtils.exportBigCsvUseDynamicDate(exportHandler, RideUserRefund.class, countFn,
                    startTime, endTime, tempFile, downloadDTO.getFileName());
            String uploadFileName = UUID.randomUUID().toString().replace("-", "");
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        } finally {
            FileUtil.del(tempFile);
        }
    }

}
